

package user

import java.text.SimpleDateFormat
import java.util.{TimeZone, Calendar}
import java.text.MessageFormat.format
import  org.apache.spark.sql.types._
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.{SparkConf, SparkContext}
import org.json4s.jackson.JsonMethods._
import java.text.MessageFormat.format
import util.Util._

object user_incr_daily {
  def main(args: Array[String]) {
    // Validate args
    if (args.length == 0) {
      println("Usage: [2015-05-25|date]")
      sys.exit(1)
    }
    val date_str=args(0).toString
    //val date_str="2015-05-24"

    val date_sdf = new SimpleDateFormat("yyyy-MM-dd")
    val daily_date = date_sdf.parse(date_str)
    val calender = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"))
    calender.setTime(daily_date)

    val (year,month,day) =(calender.get(Calendar.YEAR),calender.get(Calendar.MONTH)+1,calender.get(Calendar.DAY_OF_MONTH))

    // val filePath="hdfs:///test/daily_user/"+"day/"+date_str

    val filePath=getConfig("user.hdfsdir")+"e_device_bind_user_activated_date/"+date_str

    val sparkConf=new SparkConf().setAppName("user_inc_daily_total")
    val sc= new SparkContext(sparkConf)
    val hdfs=FileSystem.get(new Configuration())
    if(hdfs.exists(new Path(filePath)))hdfs.delete(new Path(filePath),true)
    val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
     import sqlContext._

    val user_total_sql= format(getConfig("user.day"),year.toString,month.toString,day.toString)

    val  df=sqlContext.sql(user_total_sql)
    val pk_sql=format(getConfig("active_device.pkmap"))
    val pk=sqlContext.sql(pk_sql)
    val pkmap=pk.distinct.map(row=>row.mkString("@#"))
      .subtract( df.select("product_key")
      .distinct.map(product_key=>product_key.mkString("@#")))
      .map(product_key=>product_key.toString
      +"@#"+product_key.toString+"%" +"Unknown"
      )
      .flatMap(line=>line.split("@#"))
      .map(line=>(line.split("%")(0),(line,0L)))
 //  finally Schema DataFrame = [product_key: string, uid: string, gid: string]

    // 单独算 product_key 的总数.原因是:一个用户可以属于多个分组.
    val dfcount=df.map(row=>row.mkString("@#"))
      .map(line=>line.split("@#"))
      .map( line=> line(0).toString+"%"+replaceNull(line(1)).toString)
      .distinct
      .map(line=>(line.split("%")(0),1L))
      .reduceByKey(_+_)
      .map(line=>(line._1.split("%")(0),line))

     df.map(row=>row.mkString("@#"))
       .map(line=>line.split("@#"))
       .map(line=>  line(0).toString+"%"+ replaceNull(line(2)).toString)
       .map(line=>(line,1L))
       .reduceByKey(_ + _)
       .map(line=>(line._1.split("%")(0),line))
       .++(dfcount)
       .++(pkmap)
       .map(t=>(t._1,toUserJobejct(t._2,date_str)))
       .reduceByKey((x,y)=>x merge y)
       .map(line=>compact(render(line._2)))
       .coalesce(1, shuffle = true).saveAsTextFile(filePath)

  }
}
